package com.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.auth.common.result.Result;
import com.auth.model.system.SysUser;
import com.auth.service.SysUserService;
import com.auth.vo.system.SysUserQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import utils.Md5Utils;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author tang
 * @since 2023-07-15
 */
@Api(tags ="用户管理接口")
@RestController
@RequestMapping("/admin/system/sysUser")
public class SysUserController {
    private final SysUserService sysUserService;
    public SysUserController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @ApiOperation("用户条件分页查询")
    @GetMapping("/{page}/{limit}")
    public Result userLimit(@PathVariable Long page,
                            @PathVariable Long limit,
                            SysUserQueryVo sysUserQueryVo) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        String keyword = sysUserQueryVo.getKeyword();
        String beginTime = sysUserQueryVo.getCreateTimeBegin();
        String endTime = sysUserQueryVo.getCreateTimeEnd();
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(SysUser::getUsername, keyword);
        }
        if (StringUtils.isNotBlank(beginTime)) {
            queryWrapper.ge(SysUser::getCreateTime, beginTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            queryWrapper.le(SysUser::getCreateTime, endTime);
        }
        return Result.ok(sysUserService.page(new Page<>(page, limit), queryWrapper));
    }

    @ApiOperation(value = "获取用户")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        return Result.ok(user);
    }

    @ApiOperation(value = "更新状态")
    @GetMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        sysUserService.updateStatus(id, status);
        return Result.ok();
    }

    @ApiOperation(value = "保存用户")
    @PostMapping("save")
    public Result save(@RequestBody SysUser user) {
        // 对密码进行加密
        user.setPassword(Md5Utils.encrypt(user.getPassword()));
        sysUserService.save(user);
        return Result.ok();
    }

    @ApiOperation(value = "更新用户")
    @PutMapping("update")
    public Result updateById(@RequestBody SysUser user) {
        sysUserService.updateById(user);
        return Result.ok();
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        sysUserService.removeById(id);
        return Result.ok();
    }
}

